<?php
namespace app\store\model;
use think\Model;
use think\model\concern\SoftDelete;

class StoreGroup extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    protected $globalScope = ['store_id'];
    public function scopeStore_id($query)
    {
        $query->where('store_id', StoreId());
    }

    /**
     * 获取权限组列表
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static function get_list()
    {
        $mygroup = self::get_group_list();
        $list = self::where('id','in',$mygroup)->order('id desc')->select();
        return $list;
    }

    /**
     * 获取我的子部门列表
     */
    static function get_group_list()
    {
        $groupid = cache('user_sub_group'.UserId());
        if(empty($groupid)){
            //查询我所在的组别
            $data = \app\store\model\User::where('id', UserId())->cache('user_info'.UserId(),86400,'store'.StoreId())->find();
            $groupid[] = $data['group_id'];
            $pid[] = $data['group_id'];
            do{
                //开始查询子栏目
                $sub = \app\store\model\StoreGroup::where('pid','in',$pid)->select();
                $pid = [];
                foreach ($sub as $s){
                    $groupid[] = $s['id'];
                    $pid[] = $s['id'];
                }
            }
            while(count($sub)>0);
            //保存到缓存
            cache('user_sub_group'.UserId(),$groupid,86400,'store'.StoreId());
        }
        return $groupid;
    }


}